<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="80"
    label-position="top"
  >
    <el-row class="w-full" :gutter="10">
      <el-col :span="24">
        <el-form-item label="产品名称" prop="sku_cn_title">
          <template #label>
            产品名称
            <!-- <el-button class="ml-2" size="small" @click="handleSelectProduct()"
              >选择SKU</el-button
            > -->
            <!-- <el-button size="small" @click="handleGatherIngredients">1688采集</el-button> -->
          </template>
          <el-input
            class="selectClass"
            v-model="form.sku_cn_title"
            placeholder="请输入产品名称"
          />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="采购价" prop="purchase_price">
          <el-input
            v-model="form.purchase_price"
            placeholder="CNY"
            oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="毛重" prop="gross_weight_g">
          <el-input v-model="form.gross_weight_g" placeholder="g" />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="头程发货地">
          <el-input v-model="form.shipment_point" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="7">
        <el-form-item label="尾程发货方式">
          <el-select
            class="w-full"
            v-model="form.shipment_method"
            filterable
            placeholder="请选择"
            multiple
            collapse-tags
            collapse-tags-tooltip
            clearable
          >
            <el-option
              v-for="item in shipmentMethodOptions"
              :key="item"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="货源模式">
          <el-select
            class="w-full"
            v-model="form.supply_model"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in supplyModelOptions"
              :key="item"
              :value="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="尺寸" prop="product_size_cm">
          <VGroup>
            <el-input
              style="width: 70px"
              v-model="form.product_size_cm.length"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              :controls="false"
              placeholder="长"
            />
            <el-input
              style="width: 70px"
              v-model="form.product_size_cm.width"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              :controls="false"
              placeholder="宽"
            />
            <el-input
              style="width: 135px"
              v-model="form.product_size_cm.height"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
              :controls="false"
              placeholder="高"
            >
              <template #append>cm</template>
            </el-input>
          </VGroup>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="材质">
          <el-input v-model="form.material" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="工艺说明">
          <el-input v-model="form.process_specification" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="使用场景及用途" prop="usage_scenario">
          <el-input v-model="form.usage_scenario" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="产品卖点">
          <el-input v-model="form.selling_point" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="售卖平台/站点" required>
          <div class="px-2">
            <div
              class="flex justify-start items-center w-full border p-[8px] border-[var(--base-border-color)]"
              v-for="(item, index) in form.goods_sku_prohibited_sales"
              :key="index"
            >
              <el-form-item class="mr-[8px] flex-auto !w-[580px]" label="">
                <SelectPlatformSite
                  class="bg-[var(--base-small-bg-color)]"
                  v-model:platform="item.platform_id"
                  v-model:site="item.site_code"
                  @changePlatform="changePlatform($event, index)"
                  @changeSite="changeSite($event, index)"
                >
                </SelectPlatformSite>
                <div class="w-[120px] flex items-center ml-2">
                  <div class="base-text-color px-2 cursor-pointer" @click="handleAdd()">
                    新增
                  </div>
                  <div
                    class="w-[1px] h-[18px] bg-[var(--base-left-menu-btn-color)]"
                  ></div>
                  <div
                    class="base-red-color px-2 cursor-pointer"
                    @click="handleDelete(index)"
                  >
                    删除
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="关注因素" required>
          <template #label>
            关注因素
            <el-checkbox
              class="ml-4"
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选/反选
            </el-checkbox></template
          >

          <el-checkbox-group v-model="form.factor_type" @change="handleCheckedChange">
            <el-checkbox
              v-for="item in factorType"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <SelectProduct ref="SelectProductRef" type="radio" @selected="selected"></SelectProduct>
</template>
<script name="ProductAnalysis" setup>
import SelectPlatformSite from "@/components/SelectPlatformSite";
import SelectProduct from "@/components/Dialog/SelectProduct";
import { factorType, shipmentMethodOptions, supplyModelOptions } from "../data.js";
import { ElMessage, ElMessageBox } from "element-plus";
// import { gathering } from "../api.js";

const data = reactive({
  form: {
    goods_sku_prohibited_sales: [{}],
    factor_type: [],
    product_size_cm: {},
    shipment_point: "深圳",
  },
  rules: {
    sku_cn_title: [{ required: true, message: "请输入产品名称" }],
    purchase_price: [{ required: true, message: "请输入采购价" }],
    gross_weight_g: [{ required: true, message: "请输入毛重" }],
    product_size_cm: [
      { required: true, message: "请输入尺寸" },
      {
        validator: (rule, value, callback) => {
          const { length, width, height } = value;
          const isValidNumber = (val) => !isNaN(val) && val > 0;

          if (!isValidNumber(length)) {
            callback(new Error("请输入长"));
          } else if (!isValidNumber(width)) {
            callback(new Error("请输入宽"));
          } else if (!isValidNumber(height)) {
            callback(new Error("请输入高"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    usage_scenario: [{ required: true, message: "请输入场景及用途" }],
  },
  checkAll: false,
  isIndeterminate: false,
});

const { form, rules, checkAll, isIndeterminate } = toRefs(data);

// 选择商品
const SelectProductRef = ref();
const handleSelectProduct = () => {
  SelectProductRef.value.open();
};

// 1688 采集
// const handleGatherIngredients = () => {
//   ElMessageBox.prompt("请输入1688链接", "1688采集", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     inputPattern: /^(https?:\/\/)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(\/[^\s]*)?$/,
//     inputErrorMessage: "无效的链接格式",
//   })
//     .then(async ({ value }) => {
//       try {
//         const res = await gathering({ link: value });
//         let { specification, subject, image } = res.data;
//         console.log(res.data);
//       } catch (err) {
//         console.error(err);
//       }
//     })
//     .catch(() => {});
// };

// 选中商品
const selected = (val) => {
  console.log(val);
  form.value.sku_cn_title = val.sku_cn_title;
  form.value.purchase_price = val.supplier_quotation;
  form.value.gross_weight_g = val.gross_weight_g;
  form.value.product_size_cm = val.product_size_cm;
  if (val.goods_sku_recommended_platform.length) {
    form.value.goods_sku_prohibited_sales = val.goods_sku_recommended_platform.map(
      (i) => {
        return {
          platform_name: i.platform_name,
          platform_id: i.platform_id,
          site_code: i.site_code,
          site_name: i.site_name,
        };
      }
    );
  }
};

const changePlatform = (val, index) => {
  form.value.goods_sku_prohibited_sales[index].platform_name = val;
};
const changeSite = (val, index) => {
  form.value.goods_sku_prohibited_sales[index].site_name = val;
};
const handleAdd = () => {
  form.value.goods_sku_prohibited_sales.push({});
};

const handleDelete = (index) => {
  if (form.value.goods_sku_prohibited_sales.length <= 1) {
    ElMessage.error("至少保留一条");
    return;
  }
  form.value.goods_sku_prohibited_sales.splice(index, 1);
};

const handleCheckAllChange = (val) => {
  form.value.factor_type = val ? factorType.map((i) => i.label) : [];
  isIndeterminate.value = false;
};
const handleCheckedChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === factorType.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < factorType.length;
};

const formRef = ref();
const emit = defineEmits(["submit"]);
const submit = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      const is_platform_site = form.value.goods_sku_prohibited_sales.some(
        (i) => i.platform_name && i.site_code
      );
      if (!is_platform_site) {
        return ElMessage.error("请填写售卖平台/站点");
      }
      if (form.value.factor_type.length == 0) {
        return ElMessage.error("请勾选关注因素");
      }
      const userText = getFormData();
      emit("submit", {
        type: "R1",
        userText,
      });
    }
  });
};

const getFormData = () => {
  const selectedFactorLabels = form.value?.factor_type;
  if (!Array.isArray(selectedFactorLabels)) {
    console.warn("factor_type is not a valid array");
    return "";
  }
  // 定义前言部分的常量字符串
  const preamble = `你是一位从业多年资深的产品开发经理，\n请根据以下格式，生成一份跨境出口可行性分析报告；报告中需要给出专业性的分析和建议；注意，需要区分售卖平台和售卖国的差异`;
  const dataParts = [preamble];
  if (selectedFactorLabels.length > 0) {
    dataParts.push(`1、前言`);
    selectedFactorLabels.forEach((label, index) => {
      const factor = factorType.find((item) => item.label === label);
      if (factor) {
        dataParts.push(`${index + 2}、${factor.value}`);
      }
    });
    dataParts.push(
      `${factorType.length + 2}、风险预警（以上未考虑到的方向以及你的专业建议）`
    );
    dataParts.push(
      `${factorType.length + 3}、总结（是否值得开发，未来方向，建议平台等）`
    );
  }

  // 构建产品信息部分
  const productInfoParts = [];
  // 售卖平台/站点
  if (form.value.goods_sku_prohibited_sales) {
    let platform_site = [];
    form.value.goods_sku_prohibited_sales.forEach((i) => {
      if (i.platform_name && i.site_code) {
        platform_site.push(`${i.platform_name}/${i.site_code} `);
      }
    });

    if (platform_site) {
      productInfoParts.push(`售卖平台/站点：${platform_site.join("、")}`);
    }
  }
  productInfoParts.push(`生产国：中国`);
  // 添加头程发货地
  if (form.value.shipment_point) {
    productInfoParts.push(`头程发货地：${form.value.shipment_point}`);
  }
  // 添加产品名称
  if (form.value.sku_cn_title) {
    productInfoParts.push(`产品名称：${form.value.sku_cn_title}`);
  }
  // 添加毛重
  if (form.value.gross_weight_g) {
    productInfoParts.push(`毛重：${form.value.gross_weight_g} g`);
  }
  // 添加产品尺寸
  if (
    form.value.product_size_cm.length &&
    form.value.product_size_cm.width &&
    form.value.product_size_cm.height
  ) {
    productInfoParts.push(
      `产品尺寸：${form.value.product_size_cm.length} cm x ${form.value.product_size_cm.width} cm x ${form.value.product_size_cm.height} cm`
    );
  }
  // 添加材质
  if (form.value.material) {
    productInfoParts.push(`材质：${form.value.material}`);
  }
  // 添加工艺
  if (form.value.process_specification) {
    productInfoParts.push(`工艺：${form.value.process_specification}`);
  }
  // 添加产品卖点
  if (form.value.selling_point) {
    productInfoParts.push(`产品卖点：${form.value.selling_point}`);
  }
  // 添加单件采购成本
  if (form.value.purchase_price) {
    productInfoParts.push(`单件采购成本：${form.value.purchase_price} CNY`);
  }
  // 添加使用场景及用途
  if (form.value.usage_scenario) {
    productInfoParts.push(`使用场景及用途：${form.value.usage_scenario}`);
  }
  // 添加发货方式
  if (form.value.shipment_method) {
    productInfoParts.push(`发货方式：${form.value.shipment_method}`);
  }
  // 添加采购模式
  if (form.value.supply_model) {
    productInfoParts.push(`采购模式：${form.value.supply_model}`);
  }
  // 如果 productInfoParts 不为空，则将其添加到 dataParts 中
  if (productInfoParts.length > 0) {
    dataParts.push("产品相关信息如下：");
    dataParts.push(productInfoParts.join("\n"));
  }
  // 最终拼接成完整的字符串
  const finalData = dataParts.join("\n");
  return finalData; // 如果有需要返回数据的地方
};

const reset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  init();
};

const init = () => {
  form.value = {
    goods_sku_prohibited_sales: [{}],
    factor_type: ["成本与定价（采购、头程、尾程、平台、广告、关税等）"],
    product_size_cm: {},
    shipment_point: "深圳",
    // product_size_cm: {
    //   width: 20,
    //   height: 20,
    //   length: 20,
    // },
    // shipment_point: "深圳",
    // sku_cn_title: "扫地机器人",
    // purchase_price: 1000,
    // gross_weight_g: 1000,
    // material: "塑料",
    // process_specification: " Assembly",
    // selling_point: "智能",
    // usage_scenario: "家用",
    // shipment_method: "",
    // supply_model: "自营",
    // factor_type: factorType.map((i) => i.label),
  };
  checkAll.value = false;
  isIndeterminate.value = true;
};

onMounted(() => {
  init();
});

defineExpose({ submit, reset });
</script>
<style lang="scss" scoped></style>
